//
//  BVSettingViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/16.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVSettingViewController.h"
#import "BVConst.h"
#import "AppDelegate.h"
#import "HttpTool.h"
#import "BVUserSuggestViewController.h"
#import "UIImageView+WebCache.h"
#import "BVLoginViewController.h"
@interface BVSettingViewController () <UIAlertViewDelegate>
/**
 *  更新网址
 */
@property (nonatomic, copy) NSString *trackViewUrl;
@end

@implementation BVSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置UI
    [self setupUI];
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 清除缓存
    UIButton *clearButton = [[UIButton alloc] init];
    clearButton.frame = CGRectMake(10, 84, BVScreenW - 10, 40);
    clearButton.backgroundColor = [UIColor clearColor];
    [clearButton setTitle:@"清除缓存" forState:UIControlStateNormal];
    [clearButton setTitleColor:BVBaseTextBlackColor forState:UIControlStateNormal];
    clearButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    clearButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [clearButton addTarget:self action:@selector(clearClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clearButton];
    
    // 分割线一
    UIView *oneSeperatorLine = [[UIView alloc] init];
    oneSeperatorLine.frame = CGRectMake(10, CGRectGetMaxY(clearButton.frame), BVScreenW - 2 * 10, 0.7);
    oneSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:oneSeperatorLine];
    
    // 检查更新
    UIButton *newVersionButton = [[UIButton alloc] init];
    newVersionButton.frame = CGRectMake(10, CGRectGetMaxY(oneSeperatorLine.frame), BVScreenW - 10, 40);
    newVersionButton.backgroundColor = [UIColor clearColor];
    [newVersionButton setTitle:@"检查更新" forState:UIControlStateNormal];
    [newVersionButton setTitleColor:BVTextLightGrayColor forState:UIControlStateNormal];
    newVersionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    newVersionButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [newVersionButton addTarget:self action:@selector(newVersionButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //[self.view addSubview:newVersionButton];

    // 分割线二
    UIView *twoSeperatorLine = [[UIView alloc] init];
    twoSeperatorLine.frame = CGRectMake(10, CGRectGetMaxY(clearButton.frame), BVScreenW - 2 * 10, 0.5);
    twoSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:twoSeperatorLine];
    
    // 意见反馈
    UIButton *suggestButton = [[UIButton alloc] init];
    suggestButton.frame = CGRectMake(10, CGRectGetMaxY(twoSeperatorLine.frame), BVScreenW - 10, 40);
    suggestButton.backgroundColor = [UIColor clearColor];
    [suggestButton setTitle:@"意见反馈" forState:UIControlStateNormal];
    [suggestButton setTitleColor:BVBaseTextBlackColor forState:UIControlStateNormal];
    suggestButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    suggestButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [suggestButton addTarget:self action:@selector(suggestButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:suggestButton];
    
    // 分割线三
    UIView *threeSeperatorLine = [[UIView alloc] init];
    threeSeperatorLine.frame = CGRectMake(10, 163, BVScreenW - 2 * 10, 0.5);
    threeSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:threeSeperatorLine];
}

#pragma mark -- buttonc点击事件
/**
 *  清缓存
 */
- (void)clearClick {
    
    CGFloat cachesSize = [self getCachesSize];
    if(cachesSize <=0.001){
        UIAlertController * controller = [UIAlertController alertControllerWithTitle:@"" message:@"没有缓存" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [controller addAction:sureAction];
        [self presentViewController:controller animated:YES completion:nil];
    }
    else{
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"清除缓存%.2fM",cachesSize] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSFileManager * fm = [NSFileManager defaultManager];
            NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
            BVLog(@"cachesSize  ===== %f", cachesSize);
            
            NSArray * array = [fm contentsOfDirectoryAtPath:path error:nil];
            for(NSString * str in array)
            {
                NSString * newPath = [path stringByAppendingPathComponent:str];
                [fm removeItemAtPath:newPath error:nil];
            }
            
        }];
        
        [alertController addAction:cancleAction];
        [alertController addAction:sureAction];
        
        [self presentViewController:alertController animated:YES completion:nil];

    }
}

-(CGFloat)getCachesSize{
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    return [self folderSizeAtPath:path];
}

/**
 *  遍历文件夹获得文件夹大小，返回多少M
 */
- (CGFloat ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    // 图片缓存
    folderSize += [[SDImageCache sharedImageCache] getSize];
    
    return folderSize/(1024.0*1024.0);
}

/**
 *  单个文件大小
 */
- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

/**
 *  检查新版本
 */
- (void)newVersionButtonClick {
    // 此处ID是应用ID
    NSString *urlStr = @"https://itunes.apple.com/lookup?id=1089802532";
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlStr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary * appInfo = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *infoContent = [appInfo objectForKey:@"results"];
        NSString *version = [[infoContent objectAtIndex:0] objectForKey:@"version"];
        self.trackViewUrl =  [[infoContent objectAtIndex:0] objectForKey:@"trackViewUrl"];
        
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
        
        if (![version isEqualToString:currentVersion]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"商店有最新版本了,是否更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            [alert show];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


/**
 *  意见反馈
 */
- (void)suggestButtonClick {
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * userinfo = [userDefaults objectForKey:@"USERINFO"];
    
    UIViewController * vc;
    if (userinfo[@"id"]) {
        vc = [BVUserSuggestViewController new];
    }else{
        vc = [BVLoginViewController new];
    }
    ROOTNAVPUSH(vc, YES);
}

#pragma mark -- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 更新
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackViewUrl]];
    }
}

#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
}
@end
